from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models, myserializers
from django.core.paginator import Paginator
# Create your views here.


# 登录
class Login(APIView):
    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')
        # print(name, password)

        author = models.Author.objects.filter(name=name, password=password).first()
        # print(author.id)
        if author:
            res = {}
            res['code'] = 200,
            res['message'] = "登陆成功"
            res['uid'] = author.id
            return Response(res)


# 展示作者
class AuthorList(APIView):
    def post(self, request):
        authorlist = models.Author.objects.all()
        author_ser = myserializers.AuthorSer(authorlist, many=True)
        res = {}
        res['code'] = 200
        res['message'] = author_ser.data
        return Response(res)


# 添加书籍
class AddBooks(APIView):
    def post(self, request):
        res = {}
        books_ser = myserializers.BooksSer(data=request.data)
        if books_ser.is_valid():
            books_ser.save()
            res['code'] = 200
            res['message'] = "添加成功"
        else:
            res['code'] = 401
            res['message'] = "添加失败"
        return Response(res)


# 首页展示
class Show(APIView):
    def post(self, request):
        sousuo = request.data.get('sousuo')

        try:
            current_page = request.data.get('i')
        except:
            current_page = 1

        if sousuo:
            books_list = models.Books.objects.filter(title__contains=sousuo).all()
        else:
            books_list = models.Books.objects.all()

        paginator = Paginator(books_list, 2)

        try:
            books = paginator.page(current_page)
        except:
            books = paginator.page(1)

        books_ser = myserializers.BooksSer(books, many=True)
        res = {}
        res['code'] = 200
        res['message'] = books_ser.data
        res['page_range'] = list(paginator.page_range)
        return Response(res)


# 删除
class Del(APIView):
    def post(self, request):
        d_id = request.data.get('id')

        res = {}
        if d_id:
            models.Books.objects.filter(id=d_id).delete()
            res['code'] = 200

        else:
            res['code'] = 501

        return Response(res)


# 修改
class Alter(APIView):
    def post(self, request):
        id = request.data.get('id')
        title = request.data.get('title')
        book = models.Books.objects.filter(id=id).first()
        tit = book.title
        models.Books.objects.filter(title=tit).update(title=title)
        res = {}
        res['code'] = 200,
        res['message'] = '修改成功'
        return Response(res)



